<template>
  <div class="pages"
       @mousedown.stop.prevent.left="start($event)"
       @mousemove.stop.prevent.left="drag($event)"
       @mouseup.stop.prevent.left="end($event)"
       @mouseleave.stop.prevent.left="fix($event)">
    <div class="seatSelectArea" ref="seatSelectArea">
      <div class="seatArea" :style="{width:seatAreaWidth+'px',height:seatAreaHeight+ 'px'}" v-show="x!==0 && y!==0">
        <template v-for="(seatItem,index) in seatList">
          <div ref="seatItem" :x="seatItem.x" :y="seatItem.y" class="seatItem" :key="seatItem.id"
               :style="{width:seatItemWidth+'px',height:seatItemWidth+'px',
          transform: 'translate3d(' + seatItem.translateX  + 'px,'+ seatItem.translateY + 'px,0px)',
          background:seatItem.background}" @click="handleClick(index)">
            <img v-if="seatItem.backimg" :src="seatItem.backimg">
          </div>
        </template>
      </div>
    </div>
    <drag-div :left="left" :top="top" :width="width" :height="height" v-show="showDrag"></drag-div>
  </div>
</template>

<script>
import {mapMutations, mapActions, mapState} from 'vuex'
import DragDiv from './DragDiv.vue'

export default {
  name: 'CoordinateSystem',
  components: {
    DragDiv
  },
  data() {
    return {
      seatItemWidth: 40,
      shifting: 10, // 偏移值
      left: 0,
      top: 0,
      width: 0,
      height: 0,
      startX: 0,
      startY: 0,
      showDrag: false,
      seatList: [],
      seatListBack: null,
      unSelect: '#C6E2FF',
      selecting: '#409EFF',
      selected: '#E9EEF3',
      timer: null,
      badImg: require('@/assets/images/bad.png'),
      normalImg: require('@/assets/images/normal.png'),
      goodImg: require('@/assets/images/good.png'),
      bestImg: require('@/assets/images/best.png'),
      seatArr: []
    }
  },
  watch: {
  },
  computed: {
    ...mapState({
      x: state => state.hallSeat.x,
      y: state => state.hallSeat.y,
      reset: state => state.hallSeat.reset
    }),
    seatAreaWidth() {
      return (this.seatItemWidth + this.shifting) * this.x - this.shifting
    },
    seatAreaHeight() {
      return (this.seatItemWidth + this.shifting) * this.y - this.shifting
    },
    translateValue() {
      return this.seatItemWidth + this.shifting
    },
  },
  methods: {
    ...mapMutations([
      'changeConfirmButtonLoading','changeX','changeY','changeReset']),
    ...mapActions([
      'clearHallSeat'
    ]),
    processSeats(){
       this.seatArr.forEach(item => {
        let data = {
          x:item.scol,
          y:item.srow,
          id:item.id,
          translateX: this.translateValue * (item.scol - 1),
          translateY: this.translateValue * (item.srow - 1),
          background: this.unSelect,
        }
        switch (item.recommend.toString()) {
          case '0':
            data.backimg = this.badImg
            data.background = this.selected
            break
          case '1':
            data.backimg = this.normalImg
            data.background = this.selected
            break
          case '2':
            data.backimg = this.goodImg
            data.background = this.selected
            break
          case '3':
            data.backimg = this.bestImg
            data.background = this.selected
            break
          default:
            data.backimg = null
        }
         this.seatList.push(data)
      })
    },
    refreshDom() {
      let that = this
      let seatScale = 1
      let seatScaleX = 1
      let seatScaleY = 1
      let seatSelectAreaWidth = that.$refs.seatSelectArea.offsetWidth
      let seatSelectAreaHeight = that.$refs.seatSelectArea.offsetHeight
      let seatAreaWidth = 50 * that.x - that.shifting
      let seatAreaHeight = 50 * that.y - that.shifting
      if (seatAreaWidth > seatSelectAreaWidth) {
        seatScaleX = seatSelectAreaWidth / seatAreaWidth
      }
      if (seatAreaHeight > seatSelectAreaHeight) {
        seatScaleY = seatSelectAreaHeight / seatAreaHeight
      }
      if (seatScaleX < 1 || seatScaleY < 1) {
        seatScale = seatScaleX < seatScaleY ? seatScaleX : seatScaleY
      }
      that.seatItemWidth = 40 * seatScale
      that.shifting = 10 * seatScale


/*
      for (let x = 1; x <= that.x; x++) {
        for (let y = 1; y <= that.y; y++) {
          var data = {}

          if (!that.reset && that.seatListBack != null && that.seatListBack.length > 0) {
            let temp = that.seatListBack.find((el) => (el.x === x && el.y === y))
            if (temp) {
              debugger
              let backimg = null
              switch (temp.type) {
                case '0':
                  backimg = this.badImg
                  break
                case '1':
                  backimg = this.normalImg
                  break
                case '2':
                  backimg = this.goodImg
                  break
                case '3':
                  backimg = this.bestImg
                  break
              }
              data = {
                x: x,
                y: y,
                translateX: that.translateValue * (x - 1),
                translateY: that.translateValue * (y - 1),
                background: this.selected,
                backimg: backimg
              }
              that.seatList.push(data)
              continue
            }
          }

          data = {
            x: x,
            y: y,
            translateX: that.translateValue * (x - 1),
            translateY: that.translateValue * (y - 1),
            background: this.unSelect,
            backimg: null
          }
          that.seatList.push(data)
        }
      }
*/


    },
    start(e) {
      let that = this
      // 解决mousedown导致click失效
      if (that.timer) {
        clearTimeout(that.timer)
      }
      that.timer = setTimeout(function () {
        that.showDrag = true
      }, 100)
      let x = e.clientX
      let y = e.clientY
      that.left = x
      that.top = y
      that.startX = x
      that.startY = y
    },
    drag(e) {
      let that = this
      if (that.showDrag) {
        let x = e.clientX
        let y = e.clientY
        that.left = Math.min(x, that.startX)
        that.top = Math.min(y, that.startY)
        that.width = Math.abs(x - that.startX)
        that.height = Math.abs(y - that.startY)
      }
    },
    fix() {
      if (this.showDrag) {
        let that = this
        that.left = 0
        that.top = 0
        that.width = 0
        that.height = 0
        that.startX = 0
        that.startY = 0
        that.showDrag = false
      }
    },
    end() {
      clearTimeout(this.timer)
      if (this.showDrag) {
        // 首先求出 `元素左上角` 与 `选框左上角` 在X方向较大值与Y方向较大值的交点，记为M点
        // 然后求出 `元素右下角` 与` 选框右下角` 在X方向较小值与Y方向较小值的交点，记为N点。
        // 如果M点的X坐标和Y坐标值均比N点相应的X坐标和Y坐标值小，亦即M和N可以分别构成一个矩形的左上角点和右上角点，则两矩形相交；其余情况则不相交。
        let that = this
        let seatList = that.seatList
        let dragX0 = that.left
        let dragY0 = that.top
        let dragX1 = that.left + that.width
        let dragY1 = that.top + that.height
        for (const index in seatList) {
          let mX = Math.max(dragX0, seatList[index].left)
          let mY = Math.max(dragY0, seatList[index].top)
          let nX = Math.min(dragX1, seatList[index].right)
          let nY = Math.min(dragY1, seatList[index].bottom)
          if (mX < nX && mY < nY) {
            if (that.seatList[index].background === that.selecting) {
              if (that.seatList[index].backimg === '' || that.seatList[index].backimg === null) {
                this.$set(that.seatList[index], 'background', that.unSelect)
              } else {
                this.$set(that.seatList[index], 'background', that.selected)
              }
            } else if (that.seatList[index].background === that.unSelect) {
              this.$set(that.seatList[index], 'background', that.selecting)
            } else if (that.seatList[index].background === that.selected) {
              this.$set(that.seatList[index], 'background', that.selecting)
            }
          }
        }
        that.left = 0
        that.top = 0
        that.width = 0
        that.height = 0
        that.startX = 0
        that.startY = 0
        that.showDrag = false
      }
    },
    handleClick(index) {
      let that = this
      if (that.seatList[index].background === that.selecting) {
        if (that.seatList[index].backimg === '' || that.seatList[index].backimg === null
        ) {
          this.$set(that.seatList[index], 'background', that.unSelect)
        } else {
          this.$set(that.seatList[index], 'background', that.selected)
        }
      } else if (that.seatList[index].background === that.unSelect) {
        this.$set(that.seatList[index], 'background', that.selecting)
      } else if (that.seatList[index].background === that.selected) {
        this.$set(that.seatList[index], 'background', that.selecting)
      }
    },
    setBackground(that,seatList,state,img){
      for (const index in seatList) {
        if (that.seatList[index].background === that.selecting) {
          this.$set(that.seatList[index], 'background', state)
          this.$set(that.seatList[index], 'backimg', img)
        }
      }
    },
    markSeats(e) {
      let that = this
      let seatList = that.seatList
      switch (e) {
        case 'best':
          this.setBackground(that,seatList,that.selected,that.bestImg)
          break
        case 'good':
          this.setBackground(that,seatList,that.selected,that.goodImg)
          break
        case 'normal':
          this.setBackground(that,seatList,that.selected,that.normalImg)
          break
        case 'bad':
          this.setBackground(that,seatList,that.selected,that.badImg)
          break
        case 'road':
          this.setBackground(that,seatList,that.selected,null)
      }
    },
    clearSeat() {
      let that = this
      for (const index in that.seatList) {
        this.$set(that.seatList[index], 'background', that.unSelect)
        this.$set(that.seatList[index], 'backimg', null)
      }
    },
    confirm() {
      let confirmSeatList = []
      for (const index in this.seatList) {
        // 只操作被选择的座位
        if (this.seatList[index].background === this.selected) {
          var temp = {}
          // temp.x = this.seatList[index].x
          // temp.y = this.seatList[index].y
          temp.id = this.seatList[index].id
          switch (this.seatList[index].backimg) {
            case this.badImg:
              temp.recommend = 0
              break
            case this.normalImg:
              temp.recommend = 1
              break
            case this.goodImg:
              temp.recommend = 2
              break
            case this.bestImg:
              temp.recommend = 3
              break
            default:
              temp.recommend = 4
              break
          }
          confirmSeatList.push(temp)
        }
      }
      if (confirmSeatList.length <= 0) {
        this.$notify({
          title: '警告',
          message: '请至少编辑一个座位~',
          type: 'warning',
          duration: 2000
        })
        this.changeConfirmButtonLoading(false)
        return
      }

      console.log(confirmSeatList)

      axios.post('manage/seat/upSeatInfo',{
        seatDTOList:confirmSeatList
      }).then(res => {
        console.log(res)
      }).catch(err => {
        console.log(err)
        this.$notify.error({
          title: '警告',
          message: err.message,
          duration: 2000
        })
      }).finally(() => {
        this.changeConfirmButtonLoading(false)
      })

      // axios.post('manage/lobby/upLobbySeat',{
      //   id:this.$route.params.id,
      //   col: this.x,
      //   rowNum: this.y
      // }).then(res => {
      //   this.$notify.success({
      //     title: '消息',
      //     message: res.message,
      //     duration: 2000
      //   })
      // }).catch(err => {
      //   console.log(err)
      //   this.$notify.error({
      //     title: '警告',
      //     message: err.message,
      //     duration: 2000
      //   })
      // }).finally(() => {
      //   this.changeConfirmButtonLoading(false)
      // })
      //
      // axios.post('manage/seat/genSeatMap',{
      //   lobbyId: this.$route.params.id,
      //   seatDTOList:confirmSeatList
      // }).then(res => {
      //   this.$notify.success({
      //     title: '消息',
      //     message: res.message,
      //     duration: 2000
      //   })
      // }).catch(err => {
      //   this.$notify.error({
      //     title: '警告',
      //     message: err.message,
      //     duration: 2000
      //   })
      // }).finally(() => {
      //   this.changeConfirmButtonLoading(false)
      // })

    }

  },
  created() {
    axios.get('manage/seat/getSeatInfo',{
      params: {
        id:this.$route.params.id
      }
    }).then(res => {
      this.seatArr = res.data.data
      this.processSeats()
      // 在执行 $nextTick mounted 已经执行完了
      this.$nextTick(() => {
        if ('seatItem' in this.$refs) {
          for (const item of this.$refs.seatItem) {
            let clientRect = item.getBoundingClientRect()
            let index = this.seatList.findIndex((el) => (el.x === parseInt(item.attributes.x.value) && el.y === parseInt(item.attributes.y.value)))
            let newObject = Object.assign({}, this.seatList[index], {
              top: clientRect.top,
              bottom: clientRect.bottom,
              left: clientRect.left,
              right: clientRect.right
            })
            this.$set(this.seatList, index, newObject)
          }
        }
      })
    })
  },
  mounted() {
    this.refreshDom()
  },
  updated() {
  }
}
</script>
<style scoped>
.pages {
  width: 100%;
  height: 100vh;
  padding: 100px 50px;
  box-sizing: border-box;
}

.pages .seatSelectArea {
  width: 100%;
  height: 100%;
  position: relative;
}

.pages .seatArea {
  display: flex;
  flex-wrap: wrap;
  margin: 0 auto;
  padding: 5px;
  border: 2px dashed rgba(0, 0, 0, 0.2);
  border-radius: 5px;
}

.pages .seatArea .seatItem {
  position: absolute;
  color: white;
  line-height: 40px;
  border-radius: 5px;
  user-select: none;
  display: flex;
}

.pages .seatArea .seatItem img {
  width: 100%;
  height: 100%;
  border: none;
  object-fit: cover;
}
</style>
